﻿using LiftHub.Data.TodoModels;
using Microsoft.EntityFrameworkCore;

namespace LiftHub.Data;

public class ToDoContext : DbContext
{
    public DbSet<ToDoModel> ToDos { get; set; }
    public DbSet<StepModel> Steps { get; set; }

    private string DbPath { get; }

    public ToDoContext()
    {
        var folder = Environment.SpecialFolder.LocalApplicationData;
        var path = Environment.GetFolderPath(folder);
        DbPath = Path.Join(path, "Todos.db");
    }

    protected override void OnConfiguring(DbContextOptionsBuilder options)
        => options.UseSqlite($"Data Source={DbPath}");

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
        //从当前程序集中加载 实现了IEntityTypeConfiguration接口的实体配置类
        modelBuilder.ApplyConfigurationsFromAssembly(GetType().Assembly);
        
        modelBuilder.Entity<StepModel>().HasOne(x => x.ToDo).
            WithMany(x => x.Steps).
            HasForeignKey(x => x.ToDoKey).OnDelete(DeleteBehavior.Cascade);
    }
}